import router from "@/router";
import useStore from "@/stores";
import axios from "axios";
import { Toast } from "vant";
const baseURL = "https://consult-api.itheima.net/";
const request = axios.create({
  baseURL,
  timeout: 10000,
});
request.interceptors.request.use(
  (config) => {
    const { user } = useStore();
    if (user.user.token && config.headers) {
      config.headers["Authorization"] = `Bearer ${user.user.token}`;
    }
    return config;
  },
  (err) => Promise.reject(err)
);
request.interceptors.response.use(
  (res) => {
    // 后台约定，响应成功，但是code不是10000，是业务逻辑失败
    if (res.data?.code !== 10000) {
      Toast(res.data?.message);
      return Promise.reject(res.data);
    }
    return res.data;
  },
  (err) => {
    if (err.response.status === 401) {
      const { user } = useStore();
      // 删除用户信息
      user.delUser();
      // 跳转登录，带上接口失效所在页面的地址，登录完成后回跳使用
      router.push(`/login?returnUrl=${router.currentRoute.value.fullPath}`);
    }
  }
);
export { baseURL, request };
